<?php

/**
 * 合同流水号仓库
 * @author wangwx 2015-5-19
 */

namespace common\repositories\myhtsq;
use common\entities\ContractEntity;
use common\repositories\BaseRepository;
use common\entities\myhtsq\ContractFlowCodeEntity;

class ContractFlowCodeRepository extends BaseRepository {

    /**
     * 构造函数
     * @param array $config
     */
    public function __construct($config = []) {
        parent::__construct($config);
    }

    /**
     * 获取最大合同编号流水号
     * @return int 最大合同编号流水号
     */
    public static function getMaxContractFlowCode() {
        return ContractFlowCodeEntity::find()->max('code_id');
    }
    
    /**
     * 新增合同流水号
     * @param string $contractId 合同id
     * @return boolean|string 
     */
    public static function addContractFlowCode($contractId) {
    	$contractFlowCode = new ContractFlowCodeEntity();
    	$contractFlowCode->contract_id = $contractId;
    	if($contractFlowCode->save()){
    		return $contractFlowCode->primaryKey;
    	}else{
    		return false;
    	}
    }
    
    
    /**
     * 组合生成合同编号
     * 组合规则：区域（SH）-客户简称（客户拼音字母简称，从商机系统获取）- FW20150102流水（0001）
     * @param string $areaCode 区域id
     * @param string $customerId 客户id
     * @param string $flowCode 流水号
     * @param string $contractCode 合同编号
     * @return string
     */
    public static function createContractCode($areaCode,$customerId,$flowCode,$contractCode) {
    	if ($flowCode <= 0) {
    		$flowCode = 1;
    	}
    	if (empty($contractCode)) {//新增获取
    		$timestamp = ContractEntity::getDbNowTimestamp();//取数据库时间截
    		$date = date("Ymd",$timestamp);
    		$str ='';
    		if (!empty($areaCode)) {
    			$str.=$areaCode.'-';
    		}

    		if (!empty($customerId)) {
    			$str.=$customerId.'-';
    		}
    		return strtoupper($str.'FW'.$date.sprintf("%04d", $flowCode));
    	}else{//更改 获取编号
    		$arr = explode("-FW", $contractCode);
    		$str ='';
    		if (!empty($areaCode)) {
    			$str.=$areaCode.'-';
    		}

    		if (!empty($customerId)) {
    			$str.=$customerId.'-';
    		}
    		return strtoupper($str."FW".$arr[1]);
    	}
    }
}
